﻿using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace WimClipboard
{
    public class ClipboardMonitor : IDisposable
    {
        private Window hackWindow;
        private HwndSource source = null;
        private IntPtr nextClipboardViewer;

        private IntPtr handle;

        #region Constructor / Destructor

        // Track whether Dispose has been called.
        private bool disposed = false;

        internal ClipboardMonitor()
        {
            if (Application.Current == null)
            { // Unit tests
                // We have to "show" the window in order to obtain hwnd to process WndProc messages in WPF
                this.hackWindow = new Window()
                {
                    Top = -10,
                    Left = -10,
                    Width = 0,
                    Height = 0,
                    WindowStyle = WindowStyle.None,
                    ShowInTaskbar = false,
                    ShowActivated = false,
                };

                this.hackWindow.Show();
                this.handle = new WindowInteropHelper(this.hackWindow).Handle;
                this.nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.handle);
                this.source = PresentationSource.FromVisual(this.hackWindow) as HwndSource;
                this.hackWindow.Hide();
            }
            else
            {
                this.handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
                this.nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.handle);
                this.source = PresentationSource.FromVisual(Application.Current.MainWindow) as HwndSource;
            }

            this.source.AddHook(this.WndProc);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);

            // Take this object off the finalization queue and prevent finalization
            // code for this object from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    // Dispose all managed resources
                    if (this.hackWindow != null)
                    {
                        this.hackWindow.Close();
                    }
                }

                // Clean up unmanaged resources
                ChangeClipboardChain(this.handle, this.nextClipboardViewer);
                if (this.source != null)
                {
                    this.source.RemoveHook(WndProc);
                }

                // Note disposing has been done.
                this.disposed = true;
            }
        }

        ~ClipboardMonitor()
        {
            this.Dispose(false);
        }

        #endregion Constructor / Destructor

        #region Win32 API

        private const int WM_DRAWCLIPBOARD = 0x308;
        private const int WM_CHANGECBCHAIN = 0x030D;

        [DllImport("User32.dll")]
        private static extern int SetClipboardViewer(int hWndNewViewer);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        #endregion Win32 API

        #region Clipboard content changed event

        public event EventHandler<ClipboardDataEventArgs> ClipboardContentChanged;

        private void NotifyClipboardContentChanged()
        {
            if (this.ClipboardContentChanged != null)
            {
                IDataObject iData = Clipboard.GetDataObject();
                this.ClipboardContentChanged(this, new ClipboardDataEventArgs(iData));
            }
        }

        #endregion Clipboard content changed event

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case WM_DRAWCLIPBOARD:

                    // Clipboard content changed
                    this.NotifyClipboardContentChanged();

                    // Pass the message to the next viewer.
                    SendMessage(nextClipboardViewer, msg, wParam, lParam);
                    break;

                case WM_CHANGECBCHAIN:
                    if (wParam == nextClipboardViewer)
                    {
                        // Clipboard viewer chain changed, need to fix it.
                        nextClipboardViewer = lParam;
                    }
                    else if (nextClipboardViewer != IntPtr.Zero)
                    {
                        // Pass the message to the next viewer.
                        SendMessage(nextClipboardViewer, msg, wParam, lParam);
                    }

                    break;
            }

            return IntPtr.Zero;
        }
    }

    public class ClipboardDataEventArgs : EventArgs
    {
        public IDataObject Data { get; protected set; }

        public ClipboardDataEventArgs(IDataObject data)
            : base()
        {
            this.Data = data;
        }
    }
}